import { MatchService } from 'src/modules/match/match.service';
import { Injectable } from '@nestjs/common';
import { CreateEventToPlayerDto } from './dto/create-event-to-player.dto';
import { UpdateEventToPlayerDto } from './dto/update-event-to-player.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { In, Repository } from 'typeorm';
import { EventToPlayer } from './entities/event-to-player.entity';

@Injectable()
export class EventToPlayerService {
  constructor(
    @InjectRepository(EventToPlayer)
    private readonly repository: Repository<EventToPlayer>,
    private readonly matchService: MatchService,
  ) {}
  saveList(entities: EventToPlayer[]) {
    return this.repository.save(entities);
  }
  create(createEventToPlayerDto: CreateEventToPlayerDto) {
    const entity = this.repository.create(createEventToPlayerDto);
    const res = this.repository.save(entity);
    return res;
  }

  findAll() {
    return `This action returns all eventToPlayer`;
  }

  findOne(id: number) {
    return this.repository.findOne({
      where: {
        id: id,
      },
    });
  }
  findByEventId(eventId: number) {
    return this.repository.find({
      where: {
        eventId: eventId,
      },
    });
  }

  findByEventIdAndStageOrderInEvent(
    eventId: number,
    stageOrderInEvent: number,
  ) {
    return this.repository.find({
      where: {
        eventId: eventId,
        stageOrderInEvent: stageOrderInEvent,
      },
    });
  }

  update(id: number, updateEventToPlayerDto: UpdateEventToPlayerDto) {
    // return `This action updates a #${id} eventToPlayer`;
    return this.repository.update(id, updateEventToPlayerDto);
  }

  remove(id: number) {
    return `This action removes a #${id} eventToPlayer`;
  }

  removeInEventIds(ids: number[]) {
    return this.repository.delete({
      eventId: In(ids),
    });
  }
  async removeInIds(ids: number[]) {
    return await this.repository.delete(ids);
  }
  async removeIds(ids: number[]) {
    return await this.removeInIds(ids);
  }
  async findByStageId(stageId: number): Promise<EventToPlayer[]> {
    // return this.repository.find({ where: { stageOrderInEvent: stageId } });
    const matches = await this.matchService.getByStageId(stageId);
    const e2pIdList = matches.reduce((total: Array<number>, item) => {
      const { homePlayerId, awayPlayerId } = item;
      if (!total.includes(homePlayerId)) {
        total.push(homePlayerId);
      }
      if (!total.includes(awayPlayerId)) {
        total.push(awayPlayerId);
      }
      return total;
    }, []);

    const res = await this.repository.find({
      where: {
        id: In(e2pIdList),
      },
    });
    return res;
  }
}
